from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from apps.accounts.decorators import role_required
from apps.common.mixins import RoleRequiredMixin
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from .models import SubProject
from .forms import SubProjectForm, SubProjectSearchForm, SubProjectStatusForm
from apps.projects.models import Project


@login_required
def subproject_list(request):
    """子项目列表视图"""
    form = SubProjectSearchForm(request.GET, user=request.user)
    subprojects = SubProject.objects.all().order_by('-created_at')
    
    # 根据用户角色过滤子项目
    if hasattr(request.user, 'userprofile'):
        if request.user.userprofile.role == 'college_user':
            # 二级学院用户只能看到本学院相关的子项目
            subprojects = subprojects.filter(
                project__admin_manager__userprofile__college=request.user.userprofile.college
            )
    
    # 搜索过滤
    if form.is_valid():
        search = form.cleaned_data.get('search')
        status = form.cleaned_data.get('status')
        project = form.cleaned_data.get('project')
        
        if search:
            subprojects = subprojects.filter(
                Q(name__icontains=search) | Q(description__icontains=search)
            )
        
        if status:
            subprojects = subprojects.filter(status=status)
            
        if project:
            subprojects = subprojects.filter(project=project)
    
    # 分页
    paginator = Paginator(subprojects, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'form': form,
        'page_obj': page_obj,
        'subprojects': page_obj,
    }
    return render(request, 'subprojects/subproject_list.html', context)


@login_required
def subproject_detail(request, pk):
    """子项目详情视图"""
    subproject = get_object_or_404(SubProject, pk=pk)
    
    # 权限检查
    if hasattr(request.user, 'userprofile'):
        if request.user.userprofile.role == 'college_user':
            if subproject.project.admin_manager.userprofile.college != request.user.userprofile.college:
                messages.error(request, '您没有权限查看此子项目')
                return redirect('subprojects:subproject_list')
    
    context = {
        'subproject': subproject,
    }
    return render(request, 'subprojects/subproject_detail.html', context)


@login_required
def subproject_create(request):
    """创建子项目视图"""
    project_id = request.GET.get('project')
    
    if request.method == 'POST':
        form = SubProjectForm(request.POST, user=request.user, project_id=project_id)
        if form.is_valid():
            subproject = form.save(commit=False)
            subproject.created_by = request.user
            
            # 自动设置初始状态和使用经费
            subproject.status = 'initial'  # 固定为初始状态
            subproject.used_budget = 0.00   # 固定为0
            
            # 如果是二级学院用户，自动设置所属学院
            if hasattr(request.user, 'userprofile') and request.user.userprofile.role == 'college':
                subproject.college = request.user.userprofile.college
            
            subproject.save()
            messages.success(request, f'子项目 "{subproject.name}" 创建成功！')
            return redirect('subprojects:subproject_detail', pk=subproject.pk)
    else:
        form = SubProjectForm(user=request.user, project_id=project_id)
    
    context = {
        'form': form,
        'title': '创建新子项目',
    }
    return render(request, 'subprojects/subproject_form.html', context)


@login_required
def subproject_edit(request, pk):
    """编辑子项目视图"""
    subproject = get_object_or_404(SubProject, pk=pk)
    
    # 权限检查
    if hasattr(request.user, 'userprofile'):
        if request.user.userprofile.role == 'college_user':
            if subproject.project.admin_manager.userprofile.college != request.user.userprofile.college:
                messages.error(request, '您没有权限编辑此子项目')
                return redirect('subprojects:subproject_list')
    
    if request.method == 'POST':
        form = SubProjectForm(request.POST, instance=subproject, user=request.user, is_edit=True)
        if form.is_valid():
            form.save()
            messages.success(request, f'子项目 "{subproject.name}" 更新成功！')
            return redirect('subprojects:subproject_detail', pk=subproject.pk)
    else:
        form = SubProjectForm(instance=subproject, user=request.user, is_edit=True)
    
    context = {
        'form': form,
        'subproject': subproject,
        'title': f'编辑子项目: {subproject.name}',
    }
    return render(request, 'subprojects/subproject_form.html', context)


@login_required
@require_POST
def subproject_delete(request, pk):
    """删除子项目视图"""
    subproject = get_object_or_404(SubProject, pk=pk)
    
    # 权限检查
    if hasattr(request.user, 'userprofile'):
        if request.user.userprofile.role == 'college_user':
            if subproject.project.admin_manager.userprofile.college != request.user.userprofile.college:
                return JsonResponse({'success': False, 'message': '您没有权限删除此子项目'})
    
    subproject_name = subproject.name
    subproject.delete()
    
    return JsonResponse({
        'success': True, 
        'message': f'子项目 "{subproject_name}" 已删除'
    })


@login_required
@role_required(['admin'])
def subproject_status_update(request, pk):
    """更新子项目状态（仅管理员）"""
    subproject = get_object_or_404(SubProject, pk=pk)
    
    if request.method == 'POST':
        form = SubProjectStatusForm(request.POST, instance=subproject)
        if form.is_valid():
            form.save()
            messages.success(request, f'子项目状态已更新为: {subproject.get_status_display()}')
            return redirect('subprojects:subproject_detail', pk=pk)
    else:
        form = SubProjectStatusForm(instance=subproject)
    
    context = {
        'form': form,
        'subproject': subproject,
        'title': f'更新状态: {subproject.name}',
    }
    return render(request, 'subprojects/subproject_status_form.html', context)
